package cz.vutbr.fit.xzemko01.tfmcbs.diagram.extensions.validators;

import java.util.List;

import cz.vutbr.fit.xzemko01.tfmcbs.model.Container;
import cz.vutbr.fit.xzemko01.tfmcbs.model.Interface;
import cz.vutbr.fit.xzemko01.tfmcbs.model.Requier;
import cz.vutbr.fit.xzemko01.tfmcbs.model.RequiringPort;
import cz.vutbr.fit.xzemko01.tfmcbs.model.SimpleComponent;
import cz.vutbr.fit.xzemko01.tfmcbs.model.Usage;

public class UsageLinkTargetEndValidator {
	public static boolean validate(Container container, Usage usage, Requier requier, Interface _interface) {
		if(requier == null || _interface == null) {
			return false;
		}
		
		return validateRequierAndInterfaceAreInSameContainer(requier, _interface)
				&& validateRequierNotUseInterface(requier, _interface);
	}
	
	private static boolean validateRequierAndInterfaceAreInSameContainer(Requier requier, Interface _interface) {
		Container requierContainer = null;
		if(requier instanceof RequiringPort) {
			RequiringPort port = (RequiringPort) requier;
			if(port.getComponent() != null) {
				requierContainer = port.getComponent().getContainer();
			}
		} else if(requier instanceof SimpleComponent) {
			requierContainer = ((SimpleComponent) requier).getContainer();
		}
		
		return _interface.getContainer() == requierContainer;
	}
	
	private static boolean validateRequierNotUseInterface(Requier requier, Interface _interface) {
		List<Usage> usageList = requier.getUsages();
		if(usageList == null) {
			return true;
		}
		
		for(Usage usage : usageList) {
			if(usage != null && usage.getInterface() == _interface) {
				return false;
			}
		}
		return true;
	}
}
